package com.zlj.user.dao;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.zlj.user.domain.User;

/**
 * User的数据层
 * @author bashen
 *
 *UserDao的某一实现类
 */
public class UserDaoImpl implements UserDao{
    private String path = "D:/workspace/servletFilterListener/servletLoginRegist/user.xml";
    
    /**
     * 按用户查询
     * @param username
     * @return
     */
    public User findByUsername(String username) {
    	/*
    	 * 1、得到Document
    	 * 2、Xpath查询
    	 * 3、校验查询结果是否为null,如果为null,返回null
    	 *    如果不为null，需要把element封装到User对象中
    	 */
    	
    	//创建解析器
    	SAXReader reader = new SAXReader();
    	try {
			Document dac = reader.read(path);
			//Xpath查询得到Element
			Element ele = (Element)dac.selectSingleNode("//user[@username='"+ username +"']");
			
			//3、校验查询结果是否为null,如果为null,返回null
			if(ele == null) {
				return null;
			} else {
				User user = new User();
				String attrUsername = ele.attributeValue("username");  //获取该元素的名为username的属性值
				String attrPassword = ele.attributeValue("password");  //获取该元素名为password的属性值
				user.setUsername(attrUsername);
				user.setPassword(attrPassword);
			    return user;
			}
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
    }
    
    /**
     * 添加用户
     * @param user
     */
    public void addUser(User user) {
    	/*
    	 * 1、得到Document
    	 * 2、通过Document得到root元素<users>！
    	 * 3、使用参数user,转换成Element对象
    	 * 4、把element添加到root元素中
    	 * 5、保存Document
    	 */
    	SAXReader reader = new SAXReader();
    	try {
			Document doc = reader.read(path);
			//得到根元素
			Element rootElement = doc.getRootElement();
			//通过根元素创建新元素
			Element userElement = rootElement.addElement("user");
			userElement.addAttribute("username", user.getUsername());
			userElement.addAttribute("password", user.getPassword());
			
			/*
			 * 保存文档
			 */
			//创建输出格式化器
			OutputFormat format = new OutputFormat("\t",true);  //缩进使用\t,是否换行使用true
			format.setTrimText(true); //清空原有的换行和缩进
			
			//创建XMLWriter
			XMLWriter writer;
			try {
				writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(path),"utf-8"), format);
				writer.write(doc);  //保存Document对象
				writer.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			} 
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
    }
}
